package com.example.infrastructure.domain.person.service;

import com.example.infrastructure.domain.organization.service.OrganizationDomainService;
import com.example.infrastructure.domain.person.aggregate.Person;
import com.example.infrastructure.domain.person.repo.PersonRepo;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

/**
 * TODO
 *
 * @author lxh
 * @date 2020/11/23 上午11:37
 **/
@Service
public class PersonDomainService {
    private final PersonRepo personRepo;
    private final OrganizationDomainService organizationDomainService;

    public PersonDomainService(PersonRepo personRepo, OrganizationDomainService organizationDomainService) {
        this.personRepo = personRepo;
        this.organizationDomainService = organizationDomainService;
    }

    public Optional<Person> findPerson(String personId) {
        return personRepo.findById(personId);
    }

    public List<Person> findPerson(Person example) {
        return personRepo.findPerson(Example.of(example));
    }

    public Person save(Person person) {
        if (person.getPersonId() != null) {
            throw new IllegalArgumentException("新增操作不需要ID！");
        }
        organizationDomainService
                .findByOrgId(person.getOrgId())
                .orElseThrow(() -> new IllegalArgumentException("不存在该部门： " + person.getOrgId()));
        return personRepo.save(person);
    }

    public Person update(Person person) {
        if (person.getPersonId() == null) {
            throw new IllegalArgumentException("更新操作请带上ID！");
        }
        findPerson(person.getPersonId())
                .orElseThrow(() -> new IllegalArgumentException("不存在该人员： " + person.getPersonId()));
        organizationDomainService
                .findByOrgId(person.getOrgId())
                .orElseThrow(() -> new IllegalArgumentException("不存在该部门： " + person.getOrgId()));
        return personRepo.save(person);
    }

    public void delete(Person person) {
        delete(person.getPersonId());
    }

    public void delete(String personId) {
        findPerson(personId).orElseThrow(() -> new IllegalArgumentException("不存在该人员：" + personId));
        personRepo.delete(personId);
    }
}
